var responseHandler = {};
var existAlert = false;

responseHandler = {
  message: null,
  // the bootstrap modal dialog
  dialog: null,
  preventDefaultDialog: false,
  init: function () {
    this.dialog = $('#modal');
    this.message = null;
  },
  setDialog: function(dialog) {
    this.dialog = dialog;
  },
  setMessage: function(msg) {
    this.dialog.find('#message').html(msg);
  },
  showDialog: function() {
    this.dialog.modal('show');
  },
  hideDialog: function() {
    this.dialog.modal('hide');
  },
  setPreventDefaultDialog: function(bool) {
    this.preventDefaultDialog = bool;
  },
  handleSuccessResp: function(callback) {
    var code = this.message.code;
    if (code == 200) {
      if (this.message.message.confirmed == false) {
        // this means user email not authorized
        //this.setDialog($('#unconfirmedModal'));
        this.showDialog();
      }else if (jQuery.isFunction(callback)) {
        callback(this);
      }else {
        // do nothing
      }
    }else {
      if (jQuery.isFunction(callback)) {
        callback(this);
      }
      if(this.preventDefaultDialog == false) {
        // code < 400
        var msg = this.message.message;
        this.setMessage(msg);
        this.showDialog();
      }
    };
  },
  handleErrorResp: function(callback) {
    var code = this.message.code;
    if (code > 0) {
      if(code == 555){//ajax request, show model error in ajax
        if(this.message.modelErrors){
          for(x in this.message.modelErrors){
            var e = jQuery("#"+x+"_em_");
            e.html(this.message.modelErrors[x]);
            e.show();
            var parent = e.parent().parent();
            if(!parent.hasClass("control-group")){
              parent = parent.parent();
            }
            parent.removeClass("success");
            parent.addClass("error");
          }
        }
        return;
      }
      if(!existAlert){
        existAlert = true;
        bootbox.alert(this.message.message, oneAlert);
      }
    }else if(this.message.message.fieldErrors) {
      // fieldErrors are set in message.fieldErrors
      for(var i in this.message.message.fieldErrors) {
          // find error div, then show the error message
          var errorInfoDiv = $('#' + i + '_em_');
          errorInfoDiv.html(this.message.message.fieldErrors[i][0]);
          errorInfoDiv.show();
      }
      if (jQuery.isFunction(callback)) {
        callback(this);
      }
      return false;
    }else {
      if (jQuery.isFunction(callback)) {
        callback(this);
      }
      if(this.preventDefaultDialog == false) {
        // code >= 400
        var msg = this.message.message;
        this.setMessage(msg);
        this.showDialog();
      }
    }
  },
  // the callback will only execute when response success and code is 200
  run: function(response, succeedCallback, errorCallback) {
    // checking if response is valid response object
    if(jQuery.isArray(response.success)) {
      // handle success response
      this.message = response.success[0];
      this.handleSuccessResp(succeedCallback);
    }else if(jQuery.isArray(response.errors)) {
      // handle error response
      this.message = response.errors[0];
      this.handleErrorResp(errorCallback);
    }else {
      if(typeof(response.responseText) == 'string'){
        var rs = response.responseText;
      }else if(typeof(response) == 'string'){
        var rs = response;
      }else{
        var rs = false;
      }

      if(typeof(rs) == 'string' && typeof(loginRequiredAjaxResponse) == 'string' && rs == loginRequiredAjaxResponse){
        //do nothing here
        //responseHandler.loadModal(config.url+'/site/ajaxLogin');
      }else{
        // invalid response, it may not be a json response
        // run callback if there is one
        if (jQuery.isFunction(succeedCallback)) {
          succeedCallback(response);
        }
      }
    }
  },

  loadModal: function(url){
    $.get(url, function(rs){
      responseHandler.run(rs, responseHandler.openModal)
    })
  },

  openModal: function(content){
    if($("#modal").length > 0) {
      $("#modal").html(content).modal();
    } else {
      $(content).modal()
      .on("hidden", function remove() {
        $(this).remove()
      })
    }
  },

  removeModal: function(){
    $("#modal").modal('hide');
  }
}

$(document).ready(function() {
  responseHandler.init();
});

function oneAlert(){
  existAlert = false;
}